from interface import RegularTask, TaskAtom, TaskBase
from device import DeviceBase
from copy import deepcopy
from utils.img import load_image
from ..utils import is_interface
import time
from datetime import datetime, timedelta

from ..config import KarDia_info

class BackFill(TaskAtom):
    def __init__(self, device:DeviceBase):
        super().__init__('培育室', 'BackFill', ['装填', '按品种培育'])
        self.device = device
        self.coin_eggs=[]
        self.exp_eggs=[]
        for name, info in KarDia_info['eggs'].items():
            if info['coin']:
                self.coin_eggs.append(name)
            else:
                self.exp_eggs.append(name)

    def enter_backpack(self):
        self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['装填'])
        self.device.waiting_screen_changed(func=self.device.tap, args=KarDia_info['interface_buttons'][self.interface_name]['按品种培育'])
        self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['星级'])

    def find_egg(self, egg_list:list[str]):
        for name in egg_list:
            # 遍历符合要求的蛋
            points = self.device.find_image(KarDia_info['imgs'][name])
            if len(points) > 0:
                return {'name':name,'point':points[0]}
    def run(self, coin:bool=True) -> list[str]:
        print(datetime.now(), "start", self.task_name)
        egg_list = self.coin_eggs if coin else self.exp_eggs
        ans = []
        ordered = False
        while not self.is_full():
            self.enter_backpack()
            egg = self.find_egg(egg_list)
            if egg is None:
                if ordered:
                    break
                self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['升降序'])
                ordered = True
                egg = self.find_egg(egg_list)
            if egg is not None:
                ans.append(egg['name'])
                self.device.waiting_screen_changed(func=self.device.tap, threshold=0.8, args=egg['point'])        
        return ans
    
    def is_full(self) -> bool:
        sim = 0
        while sim < 0.8:
            self.device.screenshot()
            pre = deepcopy(self.device.screen)
            self.device.swipe_left(ratio=1)
            self.device.screenshot()
            now = deepcopy(self.device.screen)
            sim = self.device.simalrity(pre, now)
        
        sim = 0
        empty_nest = KarDia_info['imgs']['空巢']
        while sim < 0.8:
            self.device.screenshot()
            points = self.device.find_image(empty_nest, y_end=self.device.screen_height//2)
            if len(points) != 0:
                return False
            pre = deepcopy(self.device.screen)
            self.device.swipe_right(ratio=1)
            self.device.screenshot()
            now = deepcopy(self.device.screen)
            sim = self.device.simalrity(pre, now)
        return True

class Sell(TaskAtom):
    def __init__(self, device:DeviceBase):
        super().__init__('培育室', 'Sell', ['派遣', '是'])
        self.device = device
    
    def run(self):
        print(datetime.now(), "start", self.task_name)
        self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['派遣'])
        self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['是'])

class LevelUp(TaskAtom):
    def __init__(self, device:DeviceBase):
        super().__init__('农场', 'LevelUp', ['战阵'])
        self.device = device
    
    def run(self, name='前锋A'):
        print(datetime.now(), "start", self.task_name)
        self.device.waiting_screen_changed(func=self.device.tap, args=KarDia_info['interface_buttons'][self.interface_name]['战阵'])
        self.device.tap(*KarDia_info['interface_buttons']['魔物战阵']['阵型A'])
        self.device.long_press(*KarDia_info['interface_buttons']['魔物战阵'][name], seconds=1)
        self.device.waiting_screen_changed(func=self.device.tap, args=KarDia_info['interface_buttons']['魔物界面']['强化'])
        for point in KarDia_info['interface_buttons']['魔物界面']['强化素材']:
            self.device.tap(*point)
        self.device.swipe_up(ratio=0.5)
        self.device.tap_image(KarDia_info['imgs']['未选中'])
        self.device.tap(*KarDia_info['interface_buttons']['魔物界面']['确定'])
        while is_interface('农场'):
            self.device.back()

class ByEggs(TaskAtom):
    def __init__(self, device:DeviceBase):
        super().__init__('市场', 'ByEggs', [])
        self.device = device
    def run(self):
        print(datetime.now(), "start", self.task_name)
        self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['买蛋'])
        for i in range(13):
            self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['11连抽'])
        self.device.tap(*KarDia_info['interface_buttons'][self.interface_name]['购买'])
        for i in range(5):
            self.device.tap(*KarDia_info['buttons']['触摸继续'])

class HatchEggsTask(RegularTask):
    def __init__(self, device: DeviceBase):
        super().__init__('HatchEggsTask', 2, task_list=[
            BackFill(device),
            Sell(device),
            LevelUp(device),
            ByEggs(device)
        ])
        self.coin = True
        self.egg_hatch_times = []
        self.next = 1
    
    def run(self):
        if self.next == 0:
            if self.taskatom_list[0].is_full():
                # 如果一开始就满了，每隔10分钟尝试出售
                self.next = 1
                self.current_priority = 0
                self.activate_time = datetime.now() + timedelta(minutes=10)
                return
            egg_list = self.taskatom_list[0].run(self.coin)
            if len(egg_list) == 0 and len(self.egg_hatch_times) == 0:
                self.coin = not self.coin
                egg_list = self.taskatom_list[0].run(self.coin)
                if len(egg_list) == 0:
                    self.next = 3
            else:
                self.current_priority = 0
                for egg in egg_list:
                    delta = datetime.strptime(
                        KarDia_info['eggs'][egg]['time'], "%H:%M:%S"
                    ) - datetime.strptime("00:00:00", "%H:%M:%S")
                    
                    self.egg_hatch_times.append(datetime.now() + delta)
                self.egg_hatch_times.sort()
                self.activate_time = self.egg_hatch_times.pop(0)
                self.next = 1 if self.coin else 2
        else:
            self.taskatom_list[self.next].run()
            self.next = 0

    def is_complete(self):
        return False

            

                
